import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
import numpy as np
from orbitP.script import config
from orbitP.layers.ITransformer_layers import TriangularCausalMask,Encoder,EncoderLayer,Decoder,DecoderLayer,FullAttention,AttentionLayer,DataEmbedding_inverted
from orbitP.layers.FeatureEncoder import FeatureEncoder

class ITransformer(nn.Module):
    """
    Paper link: https://arxiv.org/abs/2310.06625
    """
    def __init__(self,args):
        super(ITransformer, self).__init__()
        if config.useHead:
            self.feature_size = args.feature_size-1+args.embed_dim+config.stampSize
        else:
            self.feature_size = args.feature_size+config.stampSize

        self.seq_len = config.training_length
        self.pred_len = config.predicting_length
        self.focst_len = config.forecast_window
        self.output_attention = False
        self.use_norm = False
        # Embedding
        self.enc_embedding = DataEmbedding_inverted(c_in=self.seq_len, d_model=args.d_model, dropout=args.dropout)
        if config.nll:
            self.output_dim = 2*config.outputSize
        else:
            self.output_dim = config.outputSize
        self.device = torch.device(config.device)
        # Encoder-only architecture
        self.encoder = Encoder(
            [
                EncoderLayer(
                    AttentionLayer(
                        FullAttention(False, args.factor, attention_dropout=args.dropout,
                                      output_attention=self.output_attention), args.d_model, args.k),
                    args.d_model,
                    args.d_ff,
                    dropout=args.dropout,
                    # activation='ReLU' # gelu
                    activation='GELU'
                ) for l in range(args.num_layers)
            ],
            norm_layer=torch.nn.LayerNorm(args.d_model)
        )

        self.projector = nn.Linear(args.d_model, config.predicting_length, bias=True)
        self.outputLayer = nn.Linear(self.feature_size, self.output_dim, bias=True)
        if config.useHead:
            self.FeatureEncoder = FeatureEncoder(args)

    def forecast(self, x_enc, x_mark_enc, x_dec, x_mark_dec):
        x_enc = x_enc.clone()
        x_mark_enc = x_mark_enc.clone()
        x_dec = x_dec[:,:,config.axis:-1].clone()
        x_mark_dec = x_mark_dec.clone()
        if self.use_norm:
            # Normalization from Non-stationary Transformer
            means = x_enc.mean(1, keepdim=True).detach()
            x_enc = x_enc - means
            stdev = torch.sqrt(torch.var(x_enc, dim=1, keepdim=True, unbiased=False) + 1e-5)
            x_enc /= stdev

        if config.useHead:
            input = self.FeatureEncoder(x_enc, x_mark_enc, x_dec, x_mark_dec)
            enc_out = self.enc_embedding(input, None)
        else:
            enc_out = self.enc_embedding(x_enc, x_mark_enc)

        B, L, N = enc_out.shape  # B L N
        # B: batch_size;    E: d_model;
        # L: seq_len;       S: pred_len;
        # N: number of variate (tokens), can also includes covariates

        # B N E -> B N E                (B L E -> B L E in the vanilla Transformer)
        # the dimensions of embedded time series has been inverted, and then processed by native attn, layernorm and ffn modules
        enc_out, attns = self.encoder(enc_out, attn_mask=None)

        # B N E -> B N S -> B S N
        dec_out = self.projector(enc_out).permute(0, 2, 1)  # filter the covariates
        dec_out = dec_out[:,-self.pred_len:,:]
        dec_out = self.outputLayer(dec_out)

        if self.use_norm:
            # De-Normalization from Non-stationary Transformer
            dec_out = dec_out * (stdev[:, 0, :].unsqueeze(1).repeat(1, self.pred_len, 1))
            dec_out = dec_out + (means[:, 0, :].unsqueeze(1).repeat(1, self.pred_len, 1))

        return dec_out, attns

    def forward(self, src, src_mark, target, target_mark):
        dec_out, attns = self.forecast(src, src_mark, target, target_mark)

        if self.output_attention:
            return dec_out, attns
        else:
            return dec_out  # [B, L, D]